import amara

from . import get_AttributeFactoryClasses

class AttributeFactory(object):
    def __init__(self):
#        self.xml_root_classes = {}
#        self.xml_root_classes.update({u"GlobalAttribute":Attribute})
#        self.xml_root_classes.update({u"DefinitionAttribute":DefinitionAttribute})
#        self.xml_root_classes.update({u"PatchedAttribute":PatchedAttribute})
#        self.xml_root_classes.update({u"IndexedAttribute":IndexedAttribute})
#
#        self.xml_type_classes = {}
#        self.xml_type_classes.update({u"Generic":DefinitionAttributeType})
#        self.xml_type_classes.update({u"Indexed":IndexedAttributeType})
        self.xml_root_classes, self.xml_type_classes = get_AttributeFactoryClasses()
    
    def make(self, **kwargs):
        type = kwargs.get('type')
        cls = kwargs.get('cls')
        new_kwargs = kwargs.get('kwargs')
        obj = self.xml_root_classes[cls](**new_kwargs)
        #base_type = self.xml_type_classes[type](**new_kwargs)
        #obj.__dict__.update(base_type.__dict__)
        return obj
        
    def make_defined_from_global(self, **kwargs):
        kwargs.setdefault('kwargs', {})
        kwargs.setdefault('class_name', u"Generic")
        global_attrib = kwargs.get('global_attrib')
        new_kwargs = global_attrib.__dict__.copy()
        new_kwargs.update({'id':None})
        new_kwargs.update(kwargs.get('kwargs'))
        if 'attribute' in new_kwargs:
            del new_kwargs['attribute']
        cls = u"DefinitionAttribute"
        
        obj = self.xml_root_classes[cls](**new_kwargs)
        
        #base_type = self.xml_type_classes[type_str](**new_kwargs)
        #obj.__dict__.update(base_type.__dict__)
        return obj
    
    def make_patched_from_defined(self, **kwargs):
        kwargs.setdefault('kwargs', {})
        def_attrib = kwargs.get('DefinitionAttribute')
        new_kwargs = def_attrib.__dict__.copy()
        new_kwargs.update({'id':None})
        new_kwargs.update(kwargs.get('kwargs'))
        new_kwargs.update({'_DefinitionAttribute_':def_attrib})
        type_str = u"Patched"
        cls = u"PatchedAttribute"
        obj = self.xml_root_classes[cls](**new_kwargs)
        #base_type = self.xml_type_classes[type_str](**new_kwargs)
        #obj.__dict__.update(base_type.__dict__)
        return obj
    
    def make_from_xml(self, xml):
        doc = amara.parse(xml)
        xmlRoot = doc[doc.xml_properties.keys()[0]]
        cls = self.xml_root_classes[xmlRoot.class_name]
        attribute = cls(from_xml=xml)
        return attribute
#        objclass = self.xml_root_classes[xmlRoot.localName]
#        if xmlRoot.type in self.xml_type_classes:
#            objbase = self.xml_type_classes[xmlRoot.type]
#        else:
#            objbase = self.xml_type_classes[u"Generic"]
#        attribute = objclass(from_xml=xml, base_obj=objbase)
#        return attribute
